<template>
  <el-card class="list-view-card" shadow="never">
    <div class="table-header">
      <div class="title">
        <strong>任务列表</strong>
        <span class="count">共 {{ pagination.total }} 项</span>
      </div>
      <div class="header-actions">
        <el-button text class="action-button" @click="$emit('download-template')">
          <el-icon><Download /></el-icon>
          下载模板
        </el-button>
        <el-upload
          class="support-upload"
          :action="''"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleImportFile"
          accept=".xlsx,.xls"
        >
          <el-button text class="action-button">
            <el-icon><Upload /></el-icon>
            导入
          </el-button>
        </el-upload>
        <el-button text class="action-button" @click="$emit('export')">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

    <el-table
      ref="tableRef"
      :data="tasks"
      row-key="id"
      v-loading="loading"
      stripe
      highlight-current-row
      :style="{ flex: '1 1 auto' }"
      :default-sort="defaultSort"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      @sort-change="handleSortChange"
    >
      <el-table-column type="selection" width="50" fixed="left" />
      <el-table-column label="任务" min-width="300" show-overflow-tooltip sortable="custom" prop="title" fixed="left">
        <template #default="{ row }">
          <div class="task-cell">
            <div class="title-row">
              <el-link type="primary" @click.stop="$emit('open-detail', row.id)">
                {{ row.title }}
              </el-link>
            </div>
            <div class="meta">
              <span>#{{ row.id.slice(-8) }}</span>
              <span v-if="row.project_name">{{ row.project_name }}</span>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="140" align="center" sortable="custom" prop="status" column-key="status">
        <template #default="{ row }">
          <el-popover
            v-model:visible="editingPopovers[`status-${row.id}`]"
            placement="top"
            :width="200"
            popper-class="task-edit-popover"
            :trigger="'manual' as any"
            :hide-after="0"
            :close-on-click-outside="false"
            :popper-options="{ strategy: 'fixed' }"
          >
            <template #reference>
              <el-tag 
                size="small" 
                :type="statusTagType(row.status)"
                class="editable-tag"
                @click.stop="handleStatusClick(row)"
              >
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>
            <div class="popover-content" @click.stop @mousedown.stop @mouseup.stop>
              <el-select
                v-model="editingStatus"
                placeholder="请选择状态"
                style="width: 100%;"
                @click.stop
                @mousedown.stop
                @mouseup.stop
                @change="handleStatusChange"
                teleported
              >
                <el-option
                  v-for="option in statusOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                  @click.stop
                  @mousedown.stop
                />
              </el-select>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="优先级" width="120" align="center" sortable="custom" prop="priority" column-key="priority">
        <template #default="{ row }">
          <el-popover
            v-model:visible="editingPopovers[`priority-${row.id}`]"
            placement="top"
            :width="200"
            popper-class="task-edit-popover"
            :trigger="'manual' as any"
            :hide-after="0"
            :close-on-click-outside="false"
            :popper-options="{ strategy: 'fixed' }"
          >
            <template #reference>
              <el-tag 
                size="small" 
                :type="priorityTagType(row.priority)"
                class="editable-tag"
                @click.stop="handlePriorityClick(row)"
              >
                {{ getPriorityLabel(row.priority) }}
              </el-tag>
            </template>
            <div class="popover-content" @click.stop @mousedown.stop @mouseup.stop>
              <el-select
                v-model="editingPriority"
                placeholder="请选择优先级"
                style="width: 100%;"
                @click.stop
                @mousedown.stop
                @mouseup.stop
                @change="handlePriorityChange"
                teleported
              >
                <el-option
                  v-for="option in priorityOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                  @click.stop
                  @mousedown.stop
                />
              </el-select>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="任务类型" width="100" align="center" sortable="custom" prop="task_type">
        <template #default="{ row }">
          <el-tag size="small" type="info" style="cursor: default;">
            {{ getTypeLabel(row.task_type) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="负责人" width="150" show-overflow-tooltip prop="assignee_name" sortable="custom" column-key="assignee_id">
        <template #default="{ row }">
          <el-popover
            v-model:visible="editingPopovers[`assignee-${row.id}`]"
            placement="top"
            :width="250"
            popper-class="task-edit-popover"
            :trigger="'manual' as any"
            :hide-after="0"
            :close-on-click-outside="false"
            :popper-options="{ strategy: 'fixed' }"
          >
            <template #reference>
              <div 
                class="editable-text"
                @click.stop="handleAssigneeClick(row)"
                style="display: inline-flex; align-items: center;"
              >
                <UserDisplay
                  v-if="row.assignee_id"
                  :user-id="row.assignee_id"
                  :user-name="row.assignee_name"
                  :users-map="props.usersMap"
                  :show-avatar="true"
                  size="small"
                />
                <span v-else style="color: #909399;">未分配</span>
              </div>
            </template>
            <div class="popover-content" @click.stop @mousedown.stop @mouseup.stop>
              <el-select
                v-model="editingAssignee"
                placeholder="请选择负责人"
                style="width: 100%;"
                filterable
                clearable
                @click.stop
                @mousedown.stop
                @mouseup.stop
                @change="handleAssigneeChange"
                teleported
              >
                <el-option
                  v-for="user in users"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                  @click.stop
                  @mousedown.stop
                >
                  <UserDisplay
                    :user-id="user.id"
                    :user-name="user.name"
                    :users-map="props.usersMap"
                    :show-avatar="true"
                    size="small"
                  />
                </el-option>
                <el-option label="未分配" value="" @click.stop @mousedown.stop />
              </el-select>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="报告人" width="140" show-overflow-tooltip>
        <template #default="{ row }">
          <UserDisplay
            v-if="row.reporter_id"
            :user-id="row.reporter_id"
            :user-name="row.reporter_name"
            :users-map="props.usersMap"
            :show-avatar="true"
            size="small"
          />
          <span v-else style="color: #909399;">未知</span>
        </template>
      </el-table-column>

      <el-table-column label="创建者" width="140" show-overflow-tooltip>
        <template #default="{ row }">
          <UserDisplay
            v-if="row.created_by"
            :user-id="row.created_by"
            :user-name="row.creator_name || row.reporter_name"
            :users-map="props.usersMap"
            :show-avatar="true"
            size="small"
          />
          <span v-else style="color: #909399;">未知</span>
        </template>
      </el-table-column>

      <el-table-column label="开始时间" width="160" align="center" sortable="custom" prop="start_date">
        <template #default="{ row }">
          <span style="cursor: default; user-select: text; white-space: nowrap;">{{ formatDateTime(row.start_date) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="截止时间" width="160" align="center" sortable="custom" prop="due_date">
        <template #default="{ row }">
          <span :class="{ 'overdue': row.is_overdue }" style="cursor: default; user-select: text; white-space: nowrap;">
            {{ formatDateTime(row.due_date) }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="预估工时" width="100" align="center" sortable="custom" prop="estimated_hours">
        <template #default="{ row }">
          <span style="cursor: default; user-select: text;">{{ row.estimated_hours !== null && row.estimated_hours !== undefined ? `${row.estimated_hours}h` : '—' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="实际工时" width="100" align="center" sortable="custom" prop="actual_hours">
        <template #default="{ row }">
          <span style="cursor: default; user-select: text;">{{ row.actual_hours !== null && row.actual_hours !== undefined ? `${row.actual_hours}h` : '—' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="总耗时" width="100" align="center" sortable="custom" prop="total_time_spent">
        <template #default="{ row }">
          <span style="cursor: default; user-select: text;">{{ row.total_time_spent !== null && row.total_time_spent !== undefined ? `${row.total_time_spent}h` : '—' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="进度" width="100" align="center" sortable="custom" prop="progress">
        <template #default="{ row }">
          <el-progress 
            :percentage="row.progress || 0" 
            :stroke-width="6"
            :show-text="true"
            :format="() => `${row.progress || 0}%`"
          />
        </template>
      </el-table-column>

      <el-table-column label="版本" width="140" show-overflow-tooltip>
        <template #default="{ row }">
          <span v-if="row.version_name || row.version_number" style="cursor: default; user-select: text;">
            {{ row.version_number || row.version_name || '—' }}
          </span>
          <span v-else style="cursor: default; user-select: text;">—</span>
        </template>
      </el-table-column>

      <el-table-column label="评论" width="80" align="center">
        <template #default="{ row }">
          <span style="cursor: default; user-select: text;">{{ row.comment_count !== null && row.comment_count !== undefined ? row.comment_count : '—' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="附件" width="80" align="center">
        <template #default="{ row }">
          <span style="cursor: default; user-select: text;">{{ row.attachment_count !== null && row.attachment_count !== undefined ? row.attachment_count : '—' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" width="160" sortable="custom" prop="created_at">
        <template #default="{ row }">
          <span style="cursor: default; user-select: text;">{{ formatDate(row.created_at) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="更新时间" width="160" sortable="custom" prop="updated_at">
        <template #default="{ row }">
          <span style="cursor: default; user-select: text;">{{ formatDate(row.updated_at) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150" align="center" fixed="right">
        <template #default="{ row }">
          <el-button size="small" text type="primary" @click.stop="handleSplitTask(row)">
            拆分子任务
          </el-button>
          <el-button size="small" text type="danger" @click.stop="$emit('delete', row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="table-footer">
      <TaskBatchToolbar
        v-if="selectedIds.length > 0"
        :count="selectedIds.length"
        :status-options="statusOptionsForBatch || []"
        :priority-options="priorityOptionsForBatch || []"
        :users="usersForBatch || []"
        :loading="batchLoading"
        @update-status="$emit('batch-update-status')"
        @update-priority="$emit('batch-update-priority')"
        @assign="$emit('batch-assign')"
        @update-reporter="$emit('batch-update-reporter')"
        @update-project="$emit('batch-update-project')"
        @remove="$emit('batch-delete')"
        @clear="$emit('batch-clear')"
      />
      <div class="table-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next"
          :current-page="pagination.page"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 30, 50]"
          @current-change="$emit('page-change', $event)"
          @size-change="$emit('page-size-change', $event)"
        />
      </div>
    </div>

  </el-card>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import dayjs from 'dayjs'
import { Download, Upload } from '@element-plus/icons-vue'
import type { ElTable } from 'element-plus'
import type { Task } from '@/types/task'
import TaskBatchToolbar from '../components/TaskBatchToolbar.vue'
import UserDisplay from '@/components/ui/UserDisplay.vue'

interface UserOption {
  id: string
  name: string
  avatar?: string
}

const props = defineProps<{
  tasks: Task[]
  loading: boolean
  pagination: {
    page: number
    pageSize: number
    total: number
  }
  statusOptions: Array<{ value: string; label: string }>
  priorityOptions: Array<{ value: string; label: string }>
  users: UserOption[]
  selectedIds: string[]
  batchLoading?: boolean
  statusOptionsForBatch?: Array<{ value: string; label: string }>
  priorityOptionsForBatch?: Array<{ value: string; label: string }>
  usersForBatch?: Array<{ id: string; name: string }>
  sortProp?: string
  sortOrder?: string
  usersMap?: Map<string, any> | Record<string, any> | null
}>()

const emit = defineEmits<{
  (event: 'page-change', page: number): void
  (event: 'page-size-change', size: number): void
  (event: 'select-change', ids: string[]): void
  (event: 'open-detail', id: string): void
  (event: 'delete', id: string): void
  (event: 'refresh'): void
  (event: 'download-template'): void
  (event: 'import', file: File): void
  (event: 'export'): void
  (event: 'update-status', id: string, status: string): void
  (event: 'update-priority', id: string, priority: string): void
  (event: 'update-assignee', id: string, assigneeId: string | null): void
  (event: 'split-task', item: Task): void
  (event: 'batch-update-status'): void
  (event: 'batch-update-priority'): void
  (event: 'batch-assign'): void
  (event: 'batch-update-reporter'): void
  (event: 'batch-update-project'): void
  (event: 'batch-delete'): void
  (event: 'batch-clear'): void
  (event: 'sort-change', prop: string, order: string): void
}>()

const handleImportFile = (file: any) => {
  if (file.raw) {
    emit('import', file.raw)
  }
}

const tableRef = ref<InstanceType<typeof ElTable>>()

// 同步表格头部和内容的横向滚动
let scrollHandlersSetup = false
let isScrolling = false

const handleBodyScroll = (e: Event) => {
  if (isScrolling) return
  isScrolling = true
  
  const target = e.target as HTMLElement
  const scrollLeft = target.scrollLeft
  
  if (tableRef.value) {
    const headerWrapper = tableRef.value.$el?.querySelector('.el-table__header-wrapper')
    const fixedBodyWrapper = tableRef.value.$el?.querySelector('.el-table__fixed-body-wrapper')
    const fixedHeaderWrapper = tableRef.value.$el?.querySelector('.el-table__fixed-header-wrapper')
    
    if (headerWrapper && (headerWrapper as HTMLElement).scrollLeft !== scrollLeft) {
      (headerWrapper as HTMLElement).scrollLeft = scrollLeft
    }
    if (fixedBodyWrapper && (fixedBodyWrapper as HTMLElement).scrollLeft !== scrollLeft) {
      (fixedBodyWrapper as HTMLElement).scrollLeft = scrollLeft
    }
    if (fixedHeaderWrapper && (fixedHeaderWrapper as HTMLElement).scrollLeft !== scrollLeft) {
      (fixedHeaderWrapper as HTMLElement).scrollLeft = scrollLeft
    }
  }
  
  requestAnimationFrame(() => {
    isScrolling = false
  })
}

const setupScrollSync = () => {
  if (!tableRef.value || scrollHandlersSetup) return
  
  const bodyWrapper = tableRef.value.$el?.querySelector('.el-table__body-wrapper')
  const headerWrapper = tableRef.value.$el?.querySelector('.el-table__header-wrapper')
  const fixedBodyWrapper = tableRef.value.$el?.querySelector('.el-table__fixed-body-wrapper')
  const fixedHeaderWrapper = tableRef.value.$el?.querySelector('.el-table__fixed-header-wrapper')
  
  // 只监听表体的滚动，同步到表头（表头不显示滚动条，所以不需要监听表头的滚动）
  if (bodyWrapper && headerWrapper) {
    bodyWrapper.addEventListener('scroll', handleBodyScroll, { passive: true })
    scrollHandlersSetup = true
  }
  
  // 同步固定列的滚动（固定列的表头也不显示滚动条）
  if (fixedBodyWrapper && fixedHeaderWrapper) {
    fixedBodyWrapper.addEventListener('scroll', handleBodyScroll, { passive: true })
  }
}

onMounted(() => {
  nextTick(() => {
    setupScrollSync()
  })
})

// 监听数据变化，重新设置滚动同步
watch(
  () => props.tasks,
  () => {
    nextTick(() => {
      scrollHandlersSetup = false
      setupScrollSync()
    })
  }
)

const formatDate = (value?: string) => {
  if (!value) return '—'
  return dayjs(value).format('YYYY-MM-DD HH:mm')
}

const formatDateTime = (value?: string | null) => {
  if (!value) return '—'
  return dayjs(value).format('YYYY-MM-DD HH:mm:ss')
}

const getStatusLabel = (value?: string | null) => {
  if (!value) return '未设置'
  return props.statusOptions.find(option => option.value === value)?.label ?? value
}

const getPriorityLabel = (value?: string | null) => {
  if (!value) return '未设置'
  return props.priorityOptions.find(option => option.value === value)?.label ?? value
}

const getTypeLabel = (value?: string | null) => {
  if (!value) return '—'
  const typeMap: Record<string, string> = {
    feature: '功能开发',
    bug: '缺陷修复',
    improvement: '改进优化',
    documentation: '文档编写',
    test: '测试任务',
    other: '其他'
  }
  return typeMap[value] || value
}

// 处理子任务拆分
const handleSplitTask = (row: Task) => {
  emit('split-task', row)
}

const statusTagType = (status?: string | null) => {
  if (!status) return 'info'
  return 'primary'
}

const priorityTagType = (priority?: string | null) => {
  switch (priority) {
    case 'critical':
    case 'urgent':
    case 'URGENT':
      return 'danger'
    case 'high':
      return 'warning'
    case 'medium':
      return 'success'
    default:
      return 'info'
  }
}

const isSyncingSelection = ref(false)

const handleSelectionChange = (selection: Task[]) => {
  if (isSyncingSelection.value) {
    return
  }
  
  emit(
    'select-change',
    selection.map(item => item.id)
  )
}

const handleRowClick = (_row: Task) => {
  // 点击行时不自动选择
}

// 计算默认排序状态
const defaultSort = computed(() => {
  if (props.sortProp && props.sortOrder) {
    const order = props.sortOrder === 'ascending' ? 'ascending' as const : 
                  props.sortOrder === 'descending' ? 'descending' as const : 
                  undefined
    if (order) {
      return {
        prop: props.sortProp,
        order: order
      }
    }
  }
  return undefined
})

// 处理排序变化
const handleSortChange = ({ prop, order }: { prop: string; order: string | null }) => {
  emit('sort-change', prop || '', order || '')
}

// Popover 管理
const editingPopovers = ref<Record<string, boolean>>({})
const editingTaskId = ref<string | null>(null)

// 关闭所有其他 popover
const closeOtherPopovers = (exceptKey: string) => {
  Object.keys(editingPopovers.value).forEach(key => {
    if (key !== exceptKey) {
      editingPopovers.value[key] = false
    }
  })
}

// 状态编辑相关
const editingStatus = ref<string>('')

const handleStatusClick = (row: Task) => {
  const popoverKey = `status-${row.id}`
  closeOtherPopovers(popoverKey)
  editingTaskId.value = row.id
  editingStatus.value = row.status || ''
  editingPopovers.value[popoverKey] = true
}

// 状态选择后直接更新
const handleStatusChange = (val: string) => {
  if (!editingTaskId.value) return
  if (!val) return
  
  const taskId = editingTaskId.value
  const popoverKey = `status-${taskId}`
  
  // 关闭弹窗
  editingPopovers.value[popoverKey] = false
  editingTaskId.value = null
  editingStatus.value = ''
  
  // 触发更新（父组件会处理成功提示和刷新）
  emit('update-status', taskId, val)
}

// 优先级编辑相关
const editingPriority = ref<string>('')

const handlePriorityClick = (row: Task) => {
  const popoverKey = `priority-${row.id}`
  closeOtherPopovers(popoverKey)
  editingTaskId.value = row.id
  editingPriority.value = row.priority || ''
  editingPopovers.value[popoverKey] = true
}

// 优先级选择后直接更新
const handlePriorityChange = (val: string) => {
  if (!editingTaskId.value) return
  if (!val) return
  
  const taskId = editingTaskId.value
  const popoverKey = `priority-${taskId}`
  
  // 关闭弹窗
  editingPopovers.value[popoverKey] = false
  editingTaskId.value = null
  editingPriority.value = ''
  
  // 触发更新（父组件会处理成功提示和刷新）
  emit('update-priority', taskId, val)
}

// 负责人编辑相关
const editingAssignee = ref<string | null>(null)

const handleAssigneeClick = (row: Task) => {
  const popoverKey = `assignee-${row.id}`
  closeOtherPopovers(popoverKey)
  editingTaskId.value = row.id
  editingAssignee.value = row.assignee_id || null
  editingPopovers.value[popoverKey] = true
}

// 负责人选择后直接更新
const handleAssigneeChange = (val: string | null) => {
  if (!editingTaskId.value) return
  
  const taskId = editingTaskId.value
  const assigneeValue = val || null
  const popoverKey = `assignee-${taskId}`
  
  // 关闭弹窗
  editingPopovers.value[popoverKey] = false
  editingTaskId.value = null
  editingAssignee.value = null
  
  // 触发更新（父组件会处理成功提示和刷新）
  emit('update-assignee', taskId, assigneeValue)
}

// 同步表格选择状态
watch(
  () => props.selectedIds,
  async selectedIds => {
    await nextTick()
    if (!tableRef.value || isSyncingSelection.value) return
    
    const currentSelectedRows = tableRef.value.getSelectionRows() as Task[]
    const currentSelectedIds = currentSelectedRows.map(row => row.id)
    const expectedSelectedIds = props.tasks
      .filter(row => selectedIds.includes(row.id))
      .map(row => row.id)
    
    if (
      currentSelectedIds.length === expectedSelectedIds.length &&
      currentSelectedIds.every(id => expectedSelectedIds.includes(id)) &&
      expectedSelectedIds.every(id => currentSelectedIds.includes(id))
    ) {
      return
    }
    
    isSyncingSelection.value = true
    
    try {
      tableRef.value.clearSelection()
      if (!selectedIds.length) {
        return
      }
      props.tasks.forEach(row => {
        if (selectedIds.includes(row.id)) {
          tableRef.value?.toggleRowSelection(row, true)
        }
      })
    } finally {
      await nextTick()
      isSyncingSelection.value = false
    }
  },
  { immediate: true, deep: true }
)

// 监听 tasks 数据变化，重新同步选择状态
watch(
  () => props.tasks,
  async () => {
    await nextTick()
    if (!tableRef.value || isSyncingSelection.value) return
    
    isSyncingSelection.value = true
    
    try {
      if (!props.selectedIds.length) {
        tableRef.value.clearSelection()
        return
      }
      tableRef.value.clearSelection()
      props.tasks.forEach(row => {
        if (props.selectedIds.includes(row.id)) {
          tableRef.value?.toggleRowSelection(row, true)
        }
      })
    } finally {
      await nextTick()
      isSyncingSelection.value = false
    }
  },
  { deep: true }
)
</script>

<style scoped lang="scss">
.list-view-card {
  border-radius: 12px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 100%;
  min-width: 0;
  width: 100%;
  background: #ffffff;
  position: relative;
  
  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    height: 100%;
    min-height: 0;
    padding: 0;
    overflow: hidden;
  }
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
  background: #fafbfc;
  flex-shrink: 0;
  
  .title {
    display: flex;
    align-items: center;
    gap: 12px;
    color: #303133;
    
    strong {
      font-size: 16px;
      font-weight: 600;
    }
    
    .count {
      font-size: 13px;
      color: #909399;
      font-weight: 400;
    }
  }
  
  .header-actions {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .action-button {
      color: #606266;
      font-size: 13px;
      padding: 6px 12px;
      transition: all 0.2s;
      
      &:hover {
        color: #409eff;
        background-color: #ecf5ff;
      }
      
      .el-icon {
        margin-right: 4px;
        font-size: 14px;
      }
    }
  }
  
  :deep(.el-button) {
    padding: 8px 16px;
    border-radius: 6px;
    transition: all 0.2s;
    
    &:hover {
      transform: translateY(-1px);
    }
  }
}

.task-cell {
  padding: 4px 0;
  
  .title-row {
    margin-bottom: 6px;
    
    :deep(.el-link) {
      font-weight: 600;
      font-size: 14px;
      color: #303133;
      transition: all 0.2s;
      
      &:hover {
        color: #409eff;
        text-decoration: none;
      }
    }
  }
  
  .meta {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 12px;
    color: #909399;
    
    span {
      display: inline-flex;
      align-items: center;
      
      &:first-child {
        color: #909399;
        font-family: 'Monaco', 'Consolas', monospace;
      }
      
      &:not(:first-child) {
        padding: 2px 8px;
        background: #f0f2f5;
        border-radius: 4px;
        color: #606266;
      }
    }
  }
}

.table-footer {
  padding: 16px 24px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  border-top: 1px solid #ebeef5;
  background: #fafbfc;
  flex-shrink: 0;
  min-height: 60px;
  position: relative;
}

.table-pagination {
  margin-left: auto;
  
  :deep(.el-pagination) {
    margin: 0;
    
    .el-pagination__total {
      color: #606266;
      font-size: 13px;
      font-weight: 500;
      margin-right: 12px;
    }
    
    .el-pagination__sizes {
      margin-right: 12px;
      
      .el-select {
        .el-input__inner {
          height: 28px;
          line-height: 28px;
          font-size: 13px;
          border-radius: 4px;
          border-color: #dcdfe6;
          transition: all 0.2s;
          
          &:hover {
            border-color: #c0c4cc;
          }
        }
        
        &.is-focus .el-input__inner {
          border-color: #409eff;
        }
      }
    }
    
    .btn-prev,
    .btn-next {
      width: 28px;
      height: 28px;
      line-height: 28px;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      background: #ffffff;
      color: #606266;
      font-size: 14px;
      transition: all 0.2s;
      
      &:hover:not(.disabled) {
        color: #409eff;
        border-color: #409eff;
        background: #ecf5ff;
      }
      
      &.disabled {
        color: #c0c4cc;
        cursor: not-allowed;
        background: #f5f7fa;
      }
    }
    
    .el-pager {
      margin: 0 8px;
      
      li {
        min-width: 28px;
        height: 28px;
        line-height: 28px;
        border-radius: 4px;
        border: 1px solid #dcdfe6;
        background: #ffffff;
        color: #606266;
        font-size: 13px;
        font-weight: 500;
        margin: 0 2px;
        transition: all 0.2s;
        
        &:hover:not(.disabled):not(.is-active) {
          color: #409eff;
          border-color: #409eff;
          background: #ecf5ff;
        }
        
        &.is-active {
          color: #ffffff;
          background: #409eff;
          border-color: #409eff;
          font-weight: 600;
        }
        
        &.disabled {
          color: #c0c4cc;
          cursor: not-allowed;
          background: #f5f7fa;
        }
      }
    }
  }
}

.list-view-card {
  :deep(.el-table__inner-wrapper) {
    min-width: 0;
    display: flex;
    flex-direction: column;
  }
  
  :deep(.el-table) {
    flex: 1 1 auto;
    display: flex;
    flex-direction: column;
    min-width: 1290px;
    width: 100%;
    border: none;
    
    .el-table__header-wrapper {
      flex-shrink: 0;
    }
    
    .el-table__body-wrapper {
      flex: 1 1 auto;
      min-height: 0;
      overflow: visible;
    }
    
    .el-table__header {
      th {
        background: #fafbfc;
        color: #606266;
        font-weight: 600;
        font-size: 13px;
        border-bottom: 2px solid #ebeef5;
        padding: 12px 0;
        white-space: nowrap;
      }
      
      th.el-table__cell:first-child {
        text-align: center;
        
        .cell {
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
    
    .el-table__body {
      tr {
        transition: background-color 0.2s;
        
        &:hover {
          background-color: #f5f7fa;
        }
        
        td {
          border-bottom: 1px solid #f0f2f5;
          padding: 14px 8px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          user-select: text; // 允许文本选择，但不允许编辑
          
          // 确保非可编辑字段不可点击编辑
          span:not(.editable-text), div:not(.editable-tag) {
            cursor: default;
          }
        }
        
        td.el-table__cell:first-child {
          text-align: center;
          padding: 14px 0;
          
          .cell {
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }
      
      tr.el-table__row.current-row,
      tr.el-table__row.selected {
        background-color: #ecf5ff !important;
        
        &:hover {
          background-color: #d9ecff !important;
        }
        
        td {
          background-color: transparent;
        }
      }
      
      tr.el-table__row--striped {
        background-color: #fafbfc;
        
        &:hover {
          background-color: #f5f7fa;
        }
        
        &.current-row,
        &.selected {
          background-color: #e6f2ff !important;
          
          &:hover {
            background-color: #d0e7ff !important;
          }
        }
      }
    }
    
    :deep(.el-checkbox) {
      .el-checkbox__inner {
        border-color: #dcdfe6;
        transition: all 0.2s;
        
        &:hover {
          border-color: #409eff;
        }
      }
      
      &.is-checked .el-checkbox__inner {
        background-color: #409eff;
        border-color: #409eff;
      }
      
      &.is-indeterminate .el-checkbox__inner {
        background-color: #409eff;
        border-color: #409eff;
      }
    }
  }
  
  :deep(.el-table__body-wrapper) {
    flex: 1 1 auto;
    overflow-x: auto;
    overflow-y: auto;
    min-height: 0;
  }
  
  :deep(.el-table__header-wrapper) {
    overflow-x: auto;
    overflow-y: hidden;
    flex-shrink: 0;
    // 隐藏表头滚动条，但保持可滚动
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE and Edge */
    
    &::-webkit-scrollbar {
      display: none;
      width: 0;
      height: 0;
    }
  }
  
  // 隐藏固定列表头的滚动条
  :deep(.el-table__fixed-header-wrapper) {
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE and Edge */
    
    &::-webkit-scrollbar {
      display: none;
      width: 0;
      height: 0;
    }
  }
}

.editable-tag {
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    opacity: 0.8;
    transform: scale(1.05);
  }
}

.editable-text {
  cursor: pointer;
  color: #606266;
  transition: all 0.2s;
  padding: 4px 8px;
  border-radius: 4px;
  display: inline-block;
  min-width: 60px;
  
  &:hover {
    opacity: 0.8;
  }
}

// Popover 样式
:deep(.task-edit-popover) {
  padding: 8px;
  
  .popover-content {
    min-width: 180px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    
    .popover-actions {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
      margin-top: 4px;
    }
  }
}

:deep(.el-button--text) {
  padding: 6px 12px;
  border-radius: 4px;
  transition: all 0.2s;
  
  &:hover {
    background-color: #f0f2f5;
  }
  
  &.el-button--danger {
    &:hover {
      color: #f56c6c;
      background-color: #fef0f0;
    }
  }
}

.overdue {
  color: #f56c6c;
  font-weight: 500;
}

:deep(.el-progress) {
  .el-progress__text {
    font-size: 12px;
    color: #606266;
  }
}
</style>


